import { CommandDialog } from '@amcax/base';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { documentV2 } from '@app-cad/environments/nextmesh/domain';
import { createRenderTensor } from '@app-nextmesh/commands/draw/cmd-common/createTensor';
import { i18n, nmAppErrorLog } from '@app-nextmesh/common/utils';
import { ISelectOption } from '@app-nextmesh/components/types';
import { useProjectStore } from '@app-nextmesh/store/project';
import { IResultNew } from '@app-nextmesh/types';
import {
  NMToolBaseCommand,
  NMToolCmdDialogParams,
} from '@app-nextmesh/types/command';
import { clearModel } from '@app-nextmesh/utils/canvas';
import { Button, Checkbox, Col, Row, Select } from 'antd';
import { isArray } from 'lodash';
import { useEffect, useState } from 'react';
import styled from 'styled-components';

const WrapperStyle = styled.div`
  row-gap: 8px;
  width: 350px;
  padding: 0 30px 0 20px;
  padding-bottom: 8px;
  display: flex;
  flex-direction: column;

  .form-dialog_footer {
    width: 100%;
    padding: 8px 0 12px !important;
  }
`;
function CmdTensorDialog({ title, onClose }: NMToolCmdDialogParams) {
  const [tensorFormat, setTensorFormat] = useState(''); // 张量格式： principal|component
  const [resultsData, setResultsData] = useState([]); // 获取任务uuid
  const [resultsAllData, setResultsAllData] = useState<IResultNew>(null); // 获取某个任务的相关数据
  const [stepData, setStepData] = useState<ISelectOption[]>([]); // 获取步数数据
  const [fieldData, setFieldData] = useState<string[]>([]); // 获取场数数据
  const [variableData, setVariableData] = useState({}); // 获取场数据下的variable
  const [resultSelected, setResultSelected] = useState(null); // 记录选的数据源，step,field,format,layer,variable等信息
  const [formatShow, setFormatShow] = useState(false); // 是否展示Tensor选择项
  const [fieldShow, setFieldShow] = useState(false); // 是否展示Field选择项
  const [stepValue, setStepValue] = useState<number>(null); // 获取分析步数据
  const [layersOptions, setLayersOptions] = useState<
    { label: string; value: string }[]
  >([]); // 获取上表面还是下表面选择数据
  const [layersData, setLayersData] = useState(null); // 获取上表面还是下表面
  const [changeCheckboxData, setChangeCheckboxData] = useState<string[]>([]); // 获取方向多选框数据
  const [resolvedData, setResolvedData] = useState('elemental'); // 设置是全局坐标系还是局部坐标
  const [loading, setLoading] = useState(false); // 应用按钮是否在加载中
  const projectInfo = useProjectStore((state) => state.projectInfo);

  useEffect(() => {
    const resultsList = [];
    projectInfo.results.forEach((item) =>
      resultsList.push({ label: item.name, value: item.uuid }),
    );
    setResultsData(resultsList);
  }, [projectInfo]);
  useEffect(() => {
    return () => {
      clearModel();
    };
  }, []);

  // 处理不同下拉选择业务数据
  const handleResultSelectChange = (value: string | number, type: string) => {
    let params = resultSelected;
    switch (type) {
      case 'model':
        setStepValue(null);
        setFieldShow(false);
        setFormatShow(false);
        params = {
          ...params,
          model: value,
        };
        setResultSelected({
          ...params,
        });
        documentV2.resultInfo(value as string).then((req) => {
          if (req?.solve?.length !== 0) {
            const simulateData = req?.solve;
            const stepList = [];

            simulateData.forEach((item) => {
              stepList.push({
                label: '' + item.step,
                value: item.step,
              });
            });
            setStepData(stepList);
            setResultsAllData(req); // 记录全部数据
          }
        });
        break;
      case 'step':
        {
          const fieldList = [];
          let variableObject: any = variableData;
          const sValue = value as number;
          setStepValue(sValue);
          if (value || resultsAllData !== null) {
            resultsAllData?.solve[sValue]?.field.forEach((f) => {
              if (f.type === 'tensor') {
                const layerList = [];
                if (f.layer) {
                  [...new Set(f.layer)].forEach((item) =>
                    layerList.push({
                      label: item,
                      value: item,
                    }),
                  );
                  setLayersOptions(layerList);
                }
                fieldList.push(f.name);
                variableObject = {
                  ...variableObject,
                  [f.name]: f.Variable,
                };
              }
            });
            setFieldData(fieldList);
            setVariableData(variableObject);
            setFieldShow(true);

            params = {
              ...params,
              step: value,
            };
            setResultSelected({
              ...params,
            });
          }
        }
        break;
      case 'field':
        {
          const variableList = [];
          if (value) {
            variableData[value].forEach((variable) =>
              !variable.includes('_cell') ? variableList.push(variable) : '',
            );
          }
          params = {
            ...params,
            field: value,
            variable: variableList,
            variableAll: variableList,
          };
          setResultSelected({
            ...params,
          });
          setFormatShow(!!value);
        }
        break;
      case 'format':
        params = {
          ...params,
          format: value,
        };
        setResultSelected({
          ...params,
        });
        break;
    }
  };

  // checkBox 数据选择
  const onChangeCheckbox = (checkedValues: string[]) => {
    setChangeCheckboxData(checkedValues);
    if (checkedValues.length === 0) {
      MessageTip.warning(`至少选择一个选项！`);
    }
  };

  // 创建ui
  const ChexkboxUi = (value: string, lable: string) => {
    return (
      <Col span={8}>
        <Checkbox value={value}>{lable}</Checkbox>
      </Col>
    );
  };

  // 创建Checkbox ui
  const CreateCheckboxGroup = () =>
    isArray(resultSelected.variable) ? (
      resultSelected.variable.map((item) => {
        if (item.includes('xx')) {
          return ChexkboxUi(item, 'XX');
        } else if (item.includes('yy')) {
          return ChexkboxUi(item, 'YY');
        } else if (item.includes('zz')) {
          return ChexkboxUi(item, 'ZZ');
        } else if (item.includes('xy')) {
          return ChexkboxUi(item, 'XY');
        } else if (item.includes('yz')) {
          return ChexkboxUi(item, 'YZ');
        } else if (item.includes('xz')) {
          return ChexkboxUi(item, 'XZ');
        } else {
          return <></>;
        }
      })
    ) : (
      <></>
    );
  // 创建Checkbox 选项
  const CheckboxGroup = () => (
    <Checkbox.Group<string>
      style={{ width: '100%' }}
      value={changeCheckboxData}
      disabled={loading}
      onChange={onChangeCheckbox}
    >
      <Row>
        {tensorFormat === 'component' ? (
          <CreateCheckboxGroup />
        ) : (
          <>
            <Col span={8}>
              <Checkbox value='p1'>P1(Maior)</Checkbox>
            </Col>
            {resultSelected.variable.some((item) => item.includes('z')) && (
              <Col span={8}>
                <Checkbox value='p2'>P2(Mid)</Checkbox>
              </Col>
            )}
            <Col span={8}>
              <Checkbox value='p3'>P3(Minor)</Checkbox>
            </Col>
          </>
        )}
      </Row>
    </Checkbox.Group>
  );
  // Layers 上表面下表面事件
  const onChangeLayers = (value: string) => {
    setLayersData(value);
    const tVariable = [];
    resultSelected.variableAll.forEach((item) => {
      if (item.includes('_t') && value === 't') {
        tVariable.push(item);
      } else if (item.includes('_b') && value === 'b') {
        tVariable.push(item);
      }
    });
    setResultSelected({
      ...resultSelected,
      variable: tVariable,
    });
  };

  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      onClose={onClose}
    >
      <WrapperStyle>
        <Row>
          <Col span={12}>Model:</Col>
          <Col span={12}>
            <Select
              disabled={loading}
              style={{ width: 150 }}
              onChange={(value) => handleResultSelectChange(value, 'model')}
              options={resultsData}
            />
          </Col>
        </Row>
        {stepData.length !== 0 && (
          <Row>
            <Col span={12}>Step:</Col>
            <Col span={12}>
              <Select
                disabled={loading}
                style={{ width: 150 }}
                onChange={(value) => handleResultSelectChange(value, 'step')}
                value={stepValue}
                options={stepData}
              />
            </Col>
          </Row>
        )}
        {fieldShow ? (
          <Row>
            <Col span={12}>Field:</Col>
            <Col span={12}>
              <Select
                disabled={loading}
                style={{ width: 150 }}
                onChange={(value) => handleResultSelectChange(value, 'field')}
                allowClear
                options={fieldData.map((field) => ({
                  label: field,
                  value: field,
                }))}
              />
            </Col>
          </Row>
        ) : (
          ''
        )}
        {formatShow ? (
          <>
            <Row>
              <Col span={12}>Resolved in:</Col>
              <Col span={12}>
                <Select
                  disabled={loading}
                  style={{ width: 150 }}
                  value={resolvedData}
                  onChange={(value: string) => {
                    setResolvedData(value);
                  }}
                  options={[
                    { value: 'elemental', label: 'Elemental System' },
                    { value: 'global', label: 'Global System' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col span={12}>Tensor format:</Col>
              <Col span={12}>
                <Select
                  disabled={loading}
                  style={{ width: 150 }}
                  onChange={(value: string) => {
                    setTensorFormat(value);
                    setChangeCheckboxData([]);
                  }}
                  options={[
                    { value: 'principal', label: 'Principal' },
                    { value: 'component', label: 'Component' },
                  ]}
                />
              </Col>
            </Row>
            {resultSelected?.variableAll?.some(
              (item) => item.includes('_t') || item.includes('_b'),
            ) ? (
              <>
                <Row>
                  <Col span={12}>Layers:</Col>
                  <Col span={12}>
                    <Select
                      disabled={loading}
                      style={{ width: 150 }}
                      onChange={onChangeLayers}
                      options={layersOptions}
                    />
                  </Col>
                </Row>
                {layersData !== null ? <CheckboxGroup /> : ''}
              </>
            ) : (
              <CheckboxGroup />
            )}
          </>
        ) : (
          ''
        )}
        {/*{fieldShow ? (
          <div style={{ width: '300px', margin: '0 auto' }}>
            <Table
              dataSource={frameData}
              columns={columnsData}
              scroll={{ x: 300 }}
            />
          </div>
        ) : (
          ''
        )}*/}
        {formatShow ? (
          <Button
            loading={loading}
            disabled={changeCheckboxData.length === 0}
            style={{ width: '100px', marginLeft: '100px' }}
            onClick={async () => {
              if (
                resultSelected?.variable?.some(
                  (item) => !item.includes('_t') || !item.includes('_b'),
                )
              ) {
                clearModel();
                setLoading(true);
                try {
                  await createRenderTensor(
                    tensorFormat,
                    changeCheckboxData,
                    resolvedData,
                    resultSelected,
                  );
                } catch (error) {
                  nmAppErrorLog(error);
                } finally {
                  setLoading(false);
                }
              }
            }}
          >
            Apply
          </Button>
        ) : (
          ''
        )}
      </WrapperStyle>
    </CommandDialog>
  );
}
// 张量
export const cmdTensor: NMToolBaseCommand = {
  id: 'CmdTensor',
  label: 'command.draw.tensor',
  icon: 'commands/simu/tensor',
  create: (label, onClose) => (
    <CmdTensorDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
